﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace LINQToolKit.Text
{
    public sealed class XmlTemplate : TextTemplate
    {
        public const string XmlElementValue = @"\<[^\>]+\>(?<field>%[\w\.]+%)\<[^\>]+\>";
        public const string XmlAttributeValue = @"\<[^\>]+(?<field>%[\w\.]+%)[^\/]*\/\s*\>";
        public const string XmlAttributeValue2 = @"\<[^\>]+(?<field>%[\w\.]+%)[^\/]*\s*\>\s*\<\s*\/[^\>]+\>";

        public XmlTemplate(string originalContent)
            : this(originalContent, false)
        {
        }

        public XmlTemplate(string originalContent, bool emptyOnNull)
            : base(originalContent, new string[] { XmlElementValue, XmlAttributeValue, XmlAttributeValue2 }, emptyOnNull)
        {
        }

        public static XmlTemplate Load(string path)
        {
            return XmlTemplate.Load(path, Encoding.UTF8, false);
        }

        public static XmlTemplate Load(string path, Encoding encoding, bool emptyOnNull)
        {
            path.AssertNull("path");
            encoding.AssertNull("encoding");

            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }

            string originalContent = File.ReadAllText(path, encoding);
            return new XmlTemplate(originalContent, emptyOnNull);
        }
    }
}